package git.soulbgm.libreoffice;

import git.soulbgm.pojo.CmdResult;
import lombok.extern.slf4j.Slf4j;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

/**
 * @author SoulBGM
 * @version 1.0
 * @date 2020/5/20 0:35
 */
@Slf4j
public class PdfConvert {

    /**
     * 利用libreOffice将office文档转换成pdf
     *
     * @param inputFile 目标文件地址
     * @param pdfFile   输出文件夹
     * @return boolean
     */
    public static boolean convertOfficeToPdf(String inputFile, String pdfFile) {
        long start = System.currentTimeMillis();
        String command;
        boolean flag;
        String osName = System.getProperty("os.name");
        if (osName.contains("Windows")) {
            command = "soffice --headless --invisible --convert-to pdf:writer_pdf_Export " + inputFile + " --outdir " + pdfFile;
        } else {
            command = "libreoffice --headless --invisible --convert-to pdf:writer_pdf_Export " + inputFile + " --outdir " + pdfFile;
        }
        CmdResult result = exec(command);
        flag = result.isSuccess();
        long end = System.currentTimeMillis();
        log.debug("用时:{} ms", end - start);
        return flag;
    }

    public static final String LOCAL_OS;
    public static final String OS_WIN = "Win";
    public static final String OS_LINUX = "linux";

    static {
        LOCAL_OS = System.getProperty("os.name");
    }

    /**
     * 执行命令
     *
     * @param command 命令
     * @return {@link CmdResult}
     */
    public static CmdResult exec(String command) {
        Process p;
        try {
            if (LOCAL_OS.contains(OS_WIN)) {
                p = new ProcessBuilder("cmd", "/c", command).start();
            } else {
                p = new ProcessBuilder("/bin/sh", "-c", command).start();
            }
        } catch (IOException e) {
            return CmdResult.error();
        }

        try (
                InputStream inputStream = p.getInputStream();
                InputStream errorStream = p.getErrorStream()
        ) {
            String output = getStreamOutput(inputStream);
            String errorOutput = getStreamOutput(errorStream);
            if (!errorOutput.isEmpty()) {
                return CmdResult.error(errorOutput);
            } else {
                return CmdResult.success(output);
            }
        } catch (IOException e) {
            return CmdResult.error();
        }
    }

    /**
     * 得到流输出
     *
     * @param is 输入流
     * @return {@link String}
     * @throws IOException IO异常
     */
    private static String getStreamOutput(InputStream is) throws IOException {
        return getStreamOutput(is, LOCAL_OS.contains(OS_WIN) ? "GBK" : "UTF-8");
    }

    /**
     * 得到流输出
     *
     * @param is          输入流
     * @param charsetName 字符集名称
     * @return {@link String}
     * @throws IOException IO异常
     */
    private static String getStreamOutput(InputStream is, String charsetName) throws IOException {
        try (
                InputStreamReader in = new InputStreamReader(is, charsetName);
                BufferedReader br = new BufferedReader(in)
        ) {
            String line, output;
            StringBuilder sbLines = new StringBuilder();
            while ((line = br.readLine()) != null) {
                sbLines.append(line).append("\n");
            }
            output = sbLines.toString();
            return output;
        }
    }

}
